package qq2564874169.tuaotuao.fx.io;

import qq2564874169.tuaotuao.fx.utils.ExUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StringReader extends BufferedReader {
    public StringReader(Reader in) {
        super(in);
    }

    public StringReader(InputStream stream) {
        super(new InputStreamReader(stream, StandardCharsets.UTF_8));
    }

    public StringReader(File file) throws FileNotFoundException {
        this(new FileInputStream(file));
    }

    public StringReader(String filename) throws FileNotFoundException {
        this(new File(filename));
    }

    public String readToEnd() {
        try {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = this.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            throw ExUtil.toRuntime(e);
        }
    }

    public static String readToEnd(InputStream stream) {
        try (InputStream s = stream) {
            try (StringReader r = new StringReader(s)) {
                return r.readToEnd();
            }
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public void close() {
        try {
            super.close();
        } catch (IOException e) {
            //...
        }
    }
}
